import {strIsBlank} from "../utils/util.js";

export function getTemplateByType(fileType) {
    let entity = localStorage.getItem(fileType);
    if (strIsBlank(entity)) {
        entity = getEntityTemplate(fileType)
        localStorage.setItem(fileType, entity)
    }
    return entity;
}

export function getEntityTemplate(fileType) {
    switch (fileType) {
        case "Entity":
            return entityTemp();
        case "Mapper":
            return mapperTemp();
        case "Controller":
            return controllerTemp();
        case "Service":
            return serviceTemp();
        case "Impl":
            return implTemp();
        case "Xml":
            return xmlTemp();
        case "MockJs":
            return mockTemp();
        case "ApiJs":
            return apiTemp();
        case "IndexVue":
            return indexTemp();
        case "FormVue":
            return formVueTemp();
        case "Result":
            return resultTemp();
        case "SearchButtons":
            return searchButtonsTemp();
        default:
            return "";
    }
}
function mockTemp() {
    return `
import Mock from "mockjs";
import MockParamsUtil from "@/utils/MockParamsUtil";
import MockPageUtil from "@/utils/MockPageUtil";


let {<%= table.firstLowerClassName %>List} = Mock.mock({
  "<%= table.firstLowerClassName %>List|1-10": [
    {
      <% columnList.forEach(function (item) { %>
        <%= item.field %>: "@word(5)",
      <% }) %>
    }
  ]
})
/** get请求分页 */
Mock.mock(new RegExp("/<%= table.firstLowerClassName %>/page*"), 'get', (options) => {
  let paramsMap = MockParamsUtil.getUrlParams(options.url)
    const pageNum = paramsMap.get('pageNum')
    const pageSize = paramsMap.get('pageSize')
    let resultArr = [...<%= table.firstLowerClassName %>List]
  // 过滤查询条件
  resultArr = MockPageUtil.filterList(resultArr, dataJson);
  // 分页
  const data = MockPageUtil.sliceList( resultArr, pageNum, pageSize);
  return {
    code: 200,
    msg: 'success',
    data
  }
})

/**
 * 分页查询数据
 * @param params    参数
 */
Mock.mock(new RegExp("/<%= table.firstLowerClassName %>/page*"), 'post', (options) => {
  const dataJson = JSON.parse(options.body);
  console.log(dataJson, 'dataJson')
  const page = dataJson.page
  // 过滤查询条件
  <%= table.firstLowerClassName %>List = MockPageUtil.filterList(<%= table.firstLowerClassName %>List, dataJson);
  // 分页
  const data = MockPageUtil.sliceList(<%= table.firstLowerClassName %>List, page.current, page.pageSize);
  return {
    code: 200,
    msg: 'success',
    data
  }
})
// 新增
Mock.mock(new RegExp('/<%= table.firstLowerClassName %>/add*'), 'post', (options) => {
  debugger
  const body = JSON.parse(options.body)
  <%= table.firstLowerClassName %>List = [
    Mock.mock({
      ...body,
      id: "@increment(1)",
      createBy: "@cname(3)",
      createTime: "@now()",
      updateBy: "@cname(3)",
      updateTime: "@now()"
    }),
    ...<%= table.firstLowerClassName %>List
  ]
  return {
    code: 200,
    msg: 'success',
    data: '添加成功'
  }
})
// 删除
Mock.mock(new RegExp('/<%= table.firstLowerClassName %>/*'), 'delete', (options) => {
  debugger
  const id = MockParamsUtil.getPathUrlParams(options.url)
  <%= table.firstLowerClassName %>List = <%= table.firstLowerClassName %>List.filter(item => item.id != id)
  return {
    code: 200,
    msg: 'success',
    data: '删除成功'
  }
})
// 获取详情
Mock.mock(new RegExp('/<%= table.firstLowerClassName %>/*'), 'get', (options) => {
  debugger
  const id = MockParamsUtil.getPathUrlParams(options.url)
  const data = <%= table.firstLowerClassName %>List.find(item => item.id == id)
  return {
    code: 200,
    msg: 'success',
    data
  }
})
// 编辑
Mock.mock(new RegExp('/<%= table.firstLowerClassName %>/edit*'), 'post', (options) => {
  const body = JSON.parse(options.body)
  if (body.id) {
    <%= table.firstLowerClassName %>List = <%= table.firstLowerClassName %>List.map(item => {
      if (item.id == body.id) {
        return body
      }
      return item
    })
   return {
   \tcode: 200,
   \tmsg: 'success',
   \tdata: '编辑成功'
   } 
  } else {
    <%= table.firstLowerClassName %>List = [
      Mock.mock({
        ...body,
        id: "@increment(1)",
        createBy: "@cname(3)",
        createTime: "@now()",
        updateBy: "@cname(3)",
        updateTime: "@now()",
      }),
      ...<%= table.firstLowerClassName %>List
    ]
    return {
      code: 200,
      msg: 'success',
      data: '添加成功'
    }
  }

})    
`
}

export function entityTemp() {
    return `
package <%= config.basePackage %>entity;

<% entityImportList.forEach(function(item) { %>
    import <%= item %>;
<% }) %>
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description <%= table.tableName %> <%= table.tableComment %>实体类
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
<% if(config.lombok) { %>
    @Data
<% } %>
<% if(config.swagger === "knife4j") { %>
@ApiModel(value = "<%= table.tableComment %>",parent = <%= simpleSuperClass %>.class)
<% } %>
@TableName("<%= table.tableName %>")
public class <%= table.className %> extends <%= simpleSuperClass %>{
<% columnList.forEach(function (item) { %>
    /**
    * <%= item.comment %>
    */
    <% if(item.dateCol) { %>
    @JsonFormat(pattern = "<%= pattern %>")
    @DateTimeFormat(pattern = "<%= pattern %>")
    <% } %>
    <% if(config.swagger === "knife4j") { %>
        @ApiModelProperty(name =  "<%= item.comment %>")
    <% } %>
    <% if(item.field === primaryKey.field) {%>
    @TableId    
    <% }%>    
    private <%= item.javaType %> <%= item.field %>;
    <%=   %>
<% }) %>
<% if(config.page === 'mybatisPage'){%>
    @TableField(exist = false)
    private PageDTO page;
<% }%>
<% if(config.page === 'pageHelper'){%>
    @TableField(exist = false)
    private Integer currentPage;

    @TableField(exist = false)
    private Integer pageSize;
<% }%>
<% if (!config.lombok) { %>
    <% columnList.forEach(function (item) { %>
    public void set<%= item.camelCaseField %>(<%= item.javaType %> <%= item.field %>){
        this.<%= item.field %> = <%= item.field %>;
    }

    public <%= item.javaType %> get<%= item.camelCaseField %>(){
        return <%= item.field %>;
    }
    <% }) %>
    <% if(config.page === 'mybatisPage'){%>
        public void setPage(PageDTO page) {
            this.page = page;
        }
        public PageDTO getPage() {
            return page;
        }
    <% }%>
    <% if(config.page === 'pageHelper'){%>
        public void setCurrentPage(Integer currentPage) {
            this.currentPage = currentPage;
        }
        public Integer getCurrentPage() {
            return currentPage;
        }
        public void setPageSize(Integer pageSize) {
            this.pageSize = pageSize;
        }
        public Integer getPageSize() {
            return pageSize;
        }
    <% }%>
<% } %>
}

`;
}

function mapperTemp() {
    return `
package <%= config.basePackage %>mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
<% if(config.page === 'mybatisPage') {%>
import com.baomidou.mybatisplus.core.metadata.IPage;
<%}%>
import org.apache.ibatis.annotations.Param;
import <%= config.basePackage %>entity.<%= table.className %>;
import <%= config.basePackage %>service.<%= table.className %>Service;


import java.util.List;


/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description <%= table.tableName %>Mapper
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
public interface <%= table.className %>Mapper extends BaseMapper<<%= table.className %>> {

    /**
    * 分页查询
    * @param page  分页查询
    * @param <%= table.firstLowerClassName %> 查询条件
    * @return List 查询结果
    */
    <% if(config.page === 'mybatisPage') {%>
    List<<%= table.className %>> getPageByLike(IPage page,@Param("dto") <%= table.className %> <%= table.firstLowerClassName %>);
    <%}%>
    <% if(config.page === 'pageHelper') {%>
    List<<%= table.className %>> getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>);
    <%}%>
    /**
    * 批量插入
    * @param list  批量插入的数据
    * @return int  影响行数
    */
    int insertBatch(@Param("list")List<<%= table.className %>> list);

    /**
    * 批量更新
    * @param list  批量更新的数据
    * @return int  影响行数
    */
    int updateBatch(@Param("list")List<<%= table.className %>> list);
}

`;
}

function controllerTemp() {
    return `
package <%= config.basePackage %>controller;

<% if(config.swagger === "knife4j") {%>
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
<%}%>
import <%= config.basePackage %>common.Result;
import <%= config.basePackage %>entity.<%= table.className %>;
import <%= config.basePackage %>service.<%= table.className %>Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description <%= table.tableName %> <%= table.tableComment %>控制器
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
@RestController
@RequestMapping("/<%= table.firstLowerClassName %>")
<% if(config.swagger === "knife4j") { %>
    @Api(tags = "<%= table.tableComment %>")
<% } %>
public class <%= table.className %>Controller{

    @Autowired
    private <%= table.className %>Service <%= table.firstLowerClassName %>Service;

    @GetMapping("/page")
    <% if(config.swagger === "knife4j") { %>
        @ApiOperation(value = "分页查询<%= table.tableComment %>数据",notes = "分页查询描述")
    <% } %>
    public Result getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>){
        return Result.success(<%= table.firstLowerClassName %>Service.getPageByLike(<%= table.firstLowerClassName %>));
    }

    @GetMapping("/{id}")
    <% if(config.swagger === "knife4j") { %>
        @ApiOperation(value = "根据id查询<%= table.tableComment %>",notes = "详情查询描述")
    <% } %>
    public Result get<%= table.className %>ById(@PathVariable("<%= primaryKey.field%>") <%= primaryKey.javaType%> <%= primaryKey.field%>){
        return Result.success(<%= table.firstLowerClassName %>Service.getById(<%= primaryKey.field%>));
    }

    @PostMapping("/edit")
    <% if(config.swagger === "knife4j") { %>
        @ApiOperation(value = "编辑<%= table.tableComment %>",notes = "编辑描述")
    <% } %>
    public Result edit<%= table.className %>ById(@RequestBody <%= table.className %> <%= table.firstLowerClassName %>){
        return Result.buildByResult(<%= table.firstLowerClassName %>Service.edit<%= table.className %>(<%= table.firstLowerClassName %>));
    }

    /**
    * 当前为逻辑删除，
    * 需要在实体类逻辑删除字段上添加 @TableLogic(value = "1",delval = "0")
    * 对应你的逻辑删除值，
    * 真删除调用delById(id)即可
    * @param id
    * @return
    */
    @DeleteMapping("/{id}")
    <% if(config.swagger === "knife4j") { %>
        @ApiOperation(value = "根据id删除<%= table.tableComment %>",notes = "根据id删除")
    <% } %>
    public Result del<%= table.className %>ById(@PathVariable("<%= primaryKey.field%>") <%= primaryKey.javaType%> <%= primaryKey.field%>){
        return Result.buildByResult(<%= table.firstLowerClassName %>Service.removeById(<%= primaryKey.field%>));
    }
    <% if(config.exportFlag) {%>
        @GetMapping("/template")
        <% if(config.swagger === "knife4j") { %>
            @ApiOperation(value = "下载<%= table.tableComment %>导入模板")
        <% } %>
        public void downloadTemplate(HttpServletResponse response){
            <%= table.firstLowerClassName %>Service.downloadTemplate(response);
        }

        @PostMapping("/import")
        <% if(config.swagger === "knife4j") { %>
            @ApiOperation(value = "从Excel模板导入<%= table.tableComment %>数据")
        <% } %>
        public Result import4Excel(MultipartFile file){
            return Result.success(<%= table.firstLowerClassName %>Service.import4Excel(file));
        }

        @PostMapping("/export")
        <% if(config.swagger === "knife4j") { %>
            @ApiOperation(value = "导出<%= table.tableComment %>列表数据到Excel表格")
        <% } %>
        public void export2Excel(@RequestBody <%= table.className %> <%= table.firstLowerClassName %>,HttpServletResponse response){
            <%= table.firstLowerClassName %>Service.export2Excel(<%= table.firstLowerClassName %>,response);
        }
    <% } %>
}


`;
}

function serviceTemp() {
    return `
package <%= config.basePackage %>service;

import <%= config.basePackage %>common.Result;
import <%= config.basePackage %>entity.<%= table.className %>;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
<% if(config.page === 'pageHelper') {%>
import com.github.pagehelper.PageInfo;
<%}%>
<% if(config.page === 'mybatisPage') {%>
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
<%}%>
import javax.servlet.http.HttpServletResponse;

/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description <%= table.tableName %> <%= table.tableComment %>Service
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
public interface <%= table.className %>Service extends IService<<%= table.className %>>{
    <% if(config.page === 'pageHelper') {%>
    /**
    * 根据条件分页查询表格结果
    * @return Result
    */
    public PageInfo<<%= table.className %>> getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>);
    <%}%>
    <% if(config.page === 'mybatisPage') {%>
    /**
    * 根据条件分页查询表格结果
    * @return Result
    */
    public Page getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>);
    <%}%>
    /**
    * 编辑
    * @return
    */
    public Integer edit<%= table.className %>(<%= table.className %> <%= table.firstLowerClassName %>);

    <% if(config.exportFlag) {%>
        /**
        * 下载导入模板
        * @param response
        */
        public void downloadTemplate(HttpServletResponse response);

        /**
        * 从excel批量导入数据
        * @return
        */
        public Integer import4Excel(MultipartFile file);

        public void export2Excel(<%= table.className %> <%= table.firstLowerClassName %>,HttpServletResponse response);
    <%}%>
}
`;
}

function implTemp() {
    return `
package <%= config.basePackage %>service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
<% if(config.page === 'pageHelper') {%>
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
<%}%>
<% if(config.page === 'mybatisPage') {%>
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
<%}%>
import <%= config.basePackage %>common.Result;
import <%= config.basePackage %>entity.<%= table.className %>;
import <%= config.basePackage %>service.<%= table.className %>Service;
import <%= config.basePackage %>mapper.<%= table.className %>Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;


/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description <%= table.tableName %> <%= table.tableComment %>实现类
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
@Service
@Slf4j
public class <%= table.className %>ServiceImpl extends ServiceImpl<<%= table.className %>Mapper, <%= table.className %>> implements <%= table.className %>Service {

    @Autowired
    private <%= table.className %>Mapper <%= table.firstLowerClassName %>Mapper;

    <% if(config.page === 'pageHelper') {%>
    /**
    * 根据条件分页查询表格结果
    * @return Result
    */
    @Override
    public PageInfo<<%= table.className %>> getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>){
        PageHelper.startPage(<%= table.firstLowerClassName %>.getCurrentPage(),<%= table.firstLowerClassName %>.getPageSize());
        List<<%= table.className %>> pageByLike = <%= table.firstLowerClassName %>Mapper.getPageByLike(<%= table.firstLowerClassName %>);
        return new PageInfo<<%= table.className %>>(pageByLike)
    }
    <%}%>
    <% if(config.page === 'mybatisPage') {%>
    /**
    * 根据条件分页查询表格结果
    * @return Result
    */
    @Override
    public Page<<%= table.className %>> getPageByLike(<%= table.className %> <%= table.firstLowerClassName %>){
        PageDTO page = <%= table.firstLowerClassName %>.getPage();
        List<<%= table.className %>> list = <%= table.firstLowerClassName %>Mapper.getPageByLike(page, <%= table.firstLowerClassName %>);
        page.setRecords(list);
        return page;
    }
    <%}%>
    <% if(config.exportFlag) {%>
        /**
        * 下载导入模板
        * @param response
        */
        @Override
        public void downloadTemplate(HttpServletResponse response){
            throw new RuntimeException("功能暂未实现");
        }

        /**
        * 从excel批量导入数据
        * @return
        */
        @Override
        public Integer import4Excel(MultipartFile file){
            throw new RuntimeException("功能暂未实现");
        }

        /**
        * 导出为excel
        * @param response
        */
        @Override
        public void export2Excel(<%= table.className %> <%= table.firstLowerClassName %>,HttpServletResponse response){
            throw new RuntimeException("功能暂未实现");
        }
    <%}%>

    /**
    * 编辑
    * @return
    */
    @Override
    public Integer edit<%= table.className %>(<%= table.className %> <%= table.firstLowerClassName %>){
        int effect = <%= table.firstLowerClassName %>.get<%=primaryKey.camelCaseField%>() == null ?
            <%= table.firstLowerClassName %>Mapper.insert(<%= table.firstLowerClassName %>) :
            <%= table.firstLowerClassName %>Mapper.updateById(<%= table.firstLowerClassName %>);
        return effect;
    }
}


`;
}

function xmlTemp() {
    return `
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="<%= config.basePackage %>mapper.<%= table.className %>Mapper">
    <resultMap id="baseMap" type="<%= config.basePackage %>entity.<%= table.className %>">
        <%= xml.resultMap %>
    </resultMap>

    <sql id="baseColumn">
        <%= xml.baseColumn %>
    </sql>
    <sql id="baseQuery">
        select
        <include refid="baseColumn"/>
        from <%= table.tableName %> tb
    </sql>
    <insert id="insertBatch">
        <%= xml.insertBatch %>
    </insert>
    <update id="updateBatch">
        <%= xml.updateBatch %>
    </update>
    <select id="getPageByLike" resultMap="baseMap">
        <include refid="baseQuery" />
        <where>
        <% columnList.forEach(function (item) { %>
            <% if(config.page === 'pageHelper') {%>
                <%if(item.javaType === 'String'){%>
                    <if test="<%=item.field%> != null and <%=item.field%> != ''">
                        and <%=item.name%> like concat('%', #{<%=item.field%>}, '%')
                <%} else {%>
                    <if test="<%=item.field%> != null">
                        and <%=item.name%> = #{<%=item.field%>}
                <%}%>
            <%}%>
            <% if(config.page === 'mybatisPage') {%>
                <%if(item.javaType === 'String'){%>
                    <if test="dto.<%=item.field%> != null and dto.<%=item.field%> != ''">
                        and <%=item.name%> like concat('%', #{dto.<%=item.field%>}, '%')
                <%} else {%>
                    <if test="dto.<%=item.field%> != null">
                        and <%=item.name%> = #{dto.<%=item.field%>}
                <%}%>
            <%}%>
            </if>
        <% }) %>
        </where>
    </select>
</mapper>
`;
}

function apiTemp() {
    return `
import request from '@/utils/request'

/**
* 分页查询数据
* @param data
*/
export function <%= table.firstLowerClassName %>List(data) {
    return request({
        url: '/<%= table.firstLowerClassName %>/page',
        method:'post',
        data
    })
}
/**
* 根据id查询详情
*/
export function get<%= table.className %>ById(id){
    return request({
        url: \`/<%= table.firstLowerClassName %>/\${<%= primaryKey.field%>}\`,
        method:'get'
    })
}

/**
* 保存或更新详情
*/
export function edit<%= table.className %>(data){
    return request({
        url: '<%= table.firstLowerClassName %>/edit',
        method:'post',
        data
    })
}

/**
* 删除数据
*/
export function del<%= table.className %>ById(id){
    return request({
        url: \`/<%= table.firstLowerClassName %>/\${<%= primaryKey.field%>}\`,
        method:'delete'
    })
}

/**
* 导入数据
* @param url 要上传的文件地址
* @param files 文件数组
*/
export function import4excel(url,files){
    let data = new FormData()
    files.forEach(item => {data.append("files",item.raw)})
    return request({
        url,
        method: 'post',
        data
    })
}

`;
}

function indexTemp() {
    return `
    <template>
    <div style="margin-top: 20px">
        <el-form inline :model="searchForm">
            <% columnList.forEach(function (item) { %>
                <el-form-item prop="<%= item.field %>" label="<%= item.comment %>">
                    <el-input v-model="searchForm.<%= item.field %>" placeholder="<%= item.comment %>"/>
                </el-form-item>
            <% }) %>
            <el-form-item>
                <search-buttons
                        :fetch-data="fetchList"
                        :export-flag="false"
                        :add-fun="addItem"
                />
            </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" width="100" label="序号"/>
            <% columnList.forEach(function (item) { %>
                <el-table-column prop="<%= item.field %>" label="<%= item.comment %>"/>
            <% }) %>

            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-dropdown>
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>
                                <el-button type="text" @click="editItem(scope.row.id)">编辑</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" @click="itemDetail(scope.row.id)">详情</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" @click="delItem(scope.row.id)">删除</el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
                :page.sync="page.current"
                :total="total"
                :limit.sync="page.pageSize"
                @pagination="fetchList"
        />
    </div>
</template>
<script>
    /**
     * SearchButtons: 搜索按钮组件 
     * Pagination: 分页组件
     * changePage：分页切换方法
     * popAutoHeightDialog：弹窗组件 移步下方链接查看
     *  https://gitee.com/chargeduck/lesscoding_admin_ui/blob/charge_duck_permission/src/ 
     */
    import SearchButtons from '@/components/SearchButtons/index.vue'
    import Pagination from '@/components/Pagination/index.vue'
    import {del<%= table.className %>ById, <%= table.firstLowerClassName %>List} from '@/api/<%= table.firstLowerClassName %>'
    import {changePage} from '@/utils/tablePage'
    import {popAutoHeightDialog} from '@/utils/popDialog'

    export default {
        name: '<%= table.className %>Index',
        components: {SearchButtons, Pagination},
        data() {
            return {
                searchForm: {},
                page: {
                    current: 1,
                    pageSize: 10
                },
                total: 0,
                tableData: []
            }
        },
        created() {
            this.fetchList()
        },
        methods: {
            fetchList() {
                <%= table.firstLowerClassName %>List({...this.searchForm, page: this.page}).then(resp => {
                    changePage(this, resp)
                })
            },
            addItem() {
                this.popDialogForm({
                    title: '新增<%= table.tableComment %>',
                    type: 0
                })
            },
            editItem(id) {
                this.popDialogForm({
                    title: '编辑<%= table.tableComment %>',
                    type: 1,
                    id
                })
            },
            itemDetail(id) {
                this.popDialogForm({
                    title: '<%= table.tableComment %>详情',
                    type: 2,
                    id
                })
            },
            delItem(id) {
                del<%= table.className %>ById(id).then(resp => {
                    this.$message.success(resp.message)
                    this.fetchList()
                })
            },
            popDialogForm(params) {
                popAutoHeightDialog('views/<%= table.firstLowerClassName %>/form', '600px',
                    this.fetchList, params)
            }
        }
    }
</script>
<style></style>
`;
}

function formVueTemp() {
    return `
<template>
    <el-card>
        <div slot="header">
            <span>{{ popData.title }}</span>
        </div>
        <el-form :model="form" ref="form" :rules="rulesForm" label-position="left" label-width="80px">
            <el-row :gutter="20">
                <% columnList.forEach(function (item) { %>
                    <el-col :span="12">
                        <el-form-item prop="<%= item.field %>" label="<%= item.comment %>">
                            <el-input v-model="form.<%= item.field %>" placeholder="<%= item.comment %>"/>
                        </el-form-item>
                    </el-col>
                <% }) %>
            </el-row>
            <el-row v-if="popData.type !== 2">
                <el-col :span="4">
                    <el-button @click="edit" type="primary">保存</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="cancel" type="danger">取消</el-button>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
</template>
<script>
    import {edit<%= table.className %>, get<%= table.className %>ById } from '@/api/<%= table.firstLowerClassName %>'

    export default {
        name: '<%= table.className %>Form',
        props: ['popData'],
        data() {
            return {
                form: {},
                rulesForm: {
                    <% columnList.forEach(function (item) { %>
                        <%= item.field %>: [{required: true, message: '<%= item.comment %>必填', trigger: 'blur'}],
                    <% }) %>
                }
            }
        },
        created() {
            this.detail()
        },
        methods: {
            detail(){
              const id = this.popData.id
              if(id) {
                  get<%= table.className %>ById(id).then(resp => {
                      this.form = resp.data
                  })
              }
            },
            edit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                      edit<%= table.className %>(this.form).then(resp => {
                        this.$message.success(resp.message)
                        this.cancel()
                      })      
                    }
                })
            },
            cancel() {
                this.$parent.closePop()
            }
        }
    }
</script>

    `;
}

function resultTemp() {
    return `
package <%= config.basePackage %>common;

<% if(config.lombok) { %>
    import lombok.AllArgsConstructor;
    import lombok.Data;
<% } %>

/**
* @author <%= config.author %>
* @date  <%= config.date %>
* @description 通用返回实体类
* Generated By: uToolsPlugin SqlConvert
* Lesscoding Generate Service
* @version: 0.0.5
* Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
* mail to:2496290990@qq.com
*/
<% if(config.lombok) { %>
@Data
@AllArgsConstructor
<% } %>

public class Result {
    /**
     * 响应编码
     */
    private Integer code;
    /**
    * 返回信息
    */
    private String message;
    /**
    * 响应数据
    */
    private Object data;
    /**
    * 成功编码
    */
    private static final Integer SUCCESS_CODE = 200;
    /**
    * 失败编码
    */
    private static final Integer FAILED_CODE = 500;
    /**
    * 成功信息
    */
    private static final String SUCCESS_CODE = "success";
    /**
    * 失败信息
    */
    private static final String FAILED_MSG = "failed";
    
    private Result() {}
    
    <% if(!config.lombok) { %>
    public Result(Integer code, String message, Object data) {
    this.code = code;
    this.message = message;
    this.data = data;
    }
    <% } %>
    public static Result success() {
        return success(SUCCESS_MSG, true);
    }
    public static Result success(String msg, Object data) {
        return new Result(SUCCESS_CODE, msg, data);
    }
    /**
    * 通用成功返回
    *
    * @param data 要返回的数据信息
    * @return
    */
    public static Result success(Object data) {
        return success(SUCCESS_MSG, data);
    }
    
    /**
    * 通用失败返回
    *
    * @param msg 错误信息
    * @return
    */
    public static Result failed(String msg) {
        return new Result(FAILED_CODE, msg, null);
    }
    
    /**
    * 通用异常返回   用于全局异常处理器
    *
    * @param t 异常信息
    * @return
    */
    public static Result exception(Throwable t) {
        return new Result(FAILED_CODE, t.getMessage(), null);
    }
    
    /**
    * 构建通用返回
    *
    * @param code 返回状态码
    * @param msg  返回信息
    * @param data 返回数据
    * @return
    */
    public static Result build(Integer code, String msg, Object data) {
        return new Result(code, msg, data);
    }
    
    /**
    * 根据自己写的sql语句 更新结果返回    更新，新增，删除，大于0的时候返回成功，否则返回失败
    *
    * @param effectRow 受影响的行
    * @return
    */
    public static Result buildByResult(Integer effectRow) {
        return effectRow != null && effectRow > 0 ? success("操作成功") : failed("操作失败");
    }
    
    /**
    * 根据调用IService或者BaseMapper自带接口返回的结果构建Result
    *
    * @param flag 调用结果
    * @return
    */
    public static Result buildByResult(Boolean flag) {
        return flag ? success("操作成功") : failed("操作失败");
    }
}
`;
}

function searchButtonsTemp() {
    return `
    <template>
    <div>
        <el-form-item>
            <el-button type="primary" icon="el-icon-error" \@click="clearSearchForm">
                重置
            </el-button>
            <el-button type="primary" icon="el-icon-search" \@click="fetchList">
                查询
            </el-button>
            <el-button v-if="addFlag" type="primary" \@click="addFun">新增</el-button>
        </el-form-item>
        <el-dropdown v-if="exportFlag">
            <el-button type="primary">
                导入导出<i class="el-icon-arrow-down el-icon--right"/>
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                    <el-button
                            type="text"
                            icon="el-icon-download"
                            \@click="downloadTemplate"
                    >
                        模板下载
                    </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                    <el-button
                            type="text"
                            icon="el-icon-upload2"
                    >
                        导入数据
                    </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                    <el-button
                            type="text"
                            icon="el-icon-download"
                            \@click="exportMethod"
                    >
                        导出数据
                    </el-button>
                </el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
    </div>
</template>
<script>
    export default {
        name: 'SearchButtons',
        props: {
            exportFlag: {
                type: Boolean,
                default: false
            },
            fetchData: {
                type: Function
            },
            templateUrl: {
                type: String,
                default: null
            },
            exportExcel: {
                type: Function,
                default: null
            },
            addFun: {
                type: Function,
                default: null
            },
            addFlag: {
                type: Boolean,
                default: true
            }
        },
        methods: {
            clearSearchForm() {
                this.$parent.$parent.searchForm = {}
                this.fetchList()
            },
            fetchList() {
                this.fetchData()
            },
            downloadTemplate() {
                window.location.href = this.templateUrl
            },
            exportMethod() {
                this.export2Excel()
            }
        }
    }
</script>
`;
}
